package com.sky.business.sys.handler.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.Node;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.event.node.*;
import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.handler.exception.NodeNotFoundException;
import com.sky.business.sys.service.NodeService;
import com.sky.business.sys.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.SimpleTimeZone;

/**
 * 终端请求设备信息处理器
 */
@Slf4j
@Component
public class NodeReportMqttEventHandler implements MqttEventHandler {

    @Autowired
    private NodeService nodeService;

    @Autowired
    private SystemConfigService systemConfigService;

    private static SystemConfig systemConfig;

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));

    @PostConstruct
    public void init() {
        systemConfig = systemConfigService.getSystemConfig();
    }

    @Override
    public boolean match(String topic, String msg,String event) {
        return  "nodeReport".equals(event);
    }

    @Override
    public void handle(String topic, String msg) throws Exception {
        NodeReportEvent nodeReportEvent = objectMapper.readValue(msg, NodeReportEvent.class);
        //检查edgeId是否匹配
        if(!systemConfig.getEdgeId().equals(nodeReportEvent.getEdgeId())){
            log.error("收到其他边缘中心的服务器节点上报数据,edgeId:{}",nodeReportEvent.getEdgeId());
            return;
        }
        NodeInfo nodeInfo = nodeReportEvent.getNodeMetaData().getNodeInfo();
        CpuInfo cpuInfo = nodeInfo.getCpu();
        MemoryInfo memoryInfo = nodeInfo.getMemory();
        Node node = nodeService.getById(nodeReportEvent.getNodeId());
        if(node==null){
            throw new NodeNotFoundException(nodeReportEvent.getNodeId());
        }
        int gpuIdleMemory = 0;
        for (GpuInfo gpuInfo : nodeInfo.getGpuInfoList()) {
            gpuIdleMemory += gpuInfo.getFree().intValue();
        }
        node.setCpuPhysicalCore(cpuInfo.getPhysicalCores());
        node.setCpuLogicalCore(cpuInfo.getLogicalCores());
        node.setCpuIdlePercent(cpuInfo.getFreePercent().intValue());
        node.setTotalMemory(memoryInfo.getTotal().intValue());
        node.setUsedMemory(memoryInfo.getUsed().intValue());
        node.setFreeMemory(memoryInfo.getFree().intValue());
        node.setDiskFree(nodeInfo.getDisk().getFree().intValue());
        node.setGpuCount(nodeInfo.getGpuInfoList().size());
        node.setGpuIdleMemory(gpuIdleMemory);
        node.setLastHeartBeatTime(new Date());
        nodeService.updateById(node);
    }


}
